﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using Aliphant.Common;
using Aliphant.Mvvm.XEvent.Events;
using Aliphant.Mvvm.XEvent.Events.Base.SubScription;
using Aliphant.UI.AIChat.Models;
using Aliphant.UI.Windows;

namespace Aliphant.UI.AIChat.Views
{
    /// <summary>
    /// ChatRobotView.xaml 的交互逻辑
    /// </summary>
    public partial class ChatRobotView : UserControl, IPage
    {
        private WindowEvent _windowEvent;

        private SubScriptionToken _subscriptionToken1;
        private SubScriptionToken _subscriptionToken2;

        private bool _autoScroll = true;
        private double _lastVerticalOffset;

        public ChatRobotView()
        {
            InitializeComponent();

            _windowEvent = AIChatModule.EventAgent.GetEvent<WindowEvent>();

            _subscriptionToken1 = _windowEvent.Subscribe(ScrollToEndAction, (p) => p.Type == EventType.Action && p.WindowActionType == WindowActionType.Update && p.EventId == EventIds.ScrollToEnd);
            _subscriptionToken2 = _windowEvent.Subscribe(TextBoxScrollToEndAction, (p) => p.Type == EventType.Action && p.WindowActionType == WindowActionType.Update && p.EventId == EventIds.InputScrollToEnd);
        }

        private void ScrollToEndAction(WindowEvent @event)
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                if (_autoScroll)
                    mainScroll.ScrollToEnd();

                input.Focus();
            });
        }

        private void TextBoxScrollToEndAction(WindowEvent @event)
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                if (@event.Data is string msg)
                {
                    input.Text = msg;
                    input.CaretIndex = msg.Length;
                }
                input.ScrollToEnd();
            });
        }

        private void TextBox_PreviewDragOver(object sender, DragEventArgs e)
        {
            // 检查拖拽的是否是文件
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effects = DragDropEffects.Copy;
            }
            else
            {
                e.Effects = DragDropEffects.None;
            }
            e.Handled = true; // 阻止冒泡
        }

        private void TextBox_Drop(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
                // 取第一个文件路径（支持多文件拖放时可根据需求修改）
                //FilePathTextBox.Text = files[0];
                aiAgent.Text = files[0];

                _windowEvent.Publish(new WindowEvent
                {
                    Type = EventType.Action,
                    WindowActionType = WindowActionType.Edit,
                    EventId = EventIds.UpdateRobotConfig,
                    Data = files[0]
                });

                //if (DataContext is ChatRobotViewModel viewModel)
                //{
                //    viewModel.RobotConfig = files[0];
                //}
            }
        }

        public void Close()
        {
            _windowEvent.Publish(new WindowEvent
            {
                WindowActionType = WindowActionType.Close,
                Type = EventType.Action,
                EventId = EventIds.Release
            });
        }

        private void mainScroll_ScrollChanged(object sender, ScrollChangedEventArgs e)
        {
            double currentOffset = e.VerticalOffset;

            // 判断是否为向上滚动
            if (currentOffset < _lastVerticalOffset)
            {
                // 向上滚动触发的代码
                //Debug.WriteLine("向上滚动");
                _autoScroll = false;
                scrollEndBtn.Visibility = Visibility.Visible;
                _lastVerticalOffset = e.VerticalOffset;
                return;
            }
            _lastVerticalOffset = e.VerticalOffset;
            
            double maxOffset = e.ExtentHeight - e.ViewportHeight;
            // 由于浮点数精度问题，使用容差进行比较
            var nearBottom = maxOffset - e.VerticalOffset <= 70;
            if (nearBottom)
            {
                _autoScroll = true;
                scrollEndBtn.Visibility = Visibility.Collapsed;
            }

        }

        private void scrollEndBtn_Click(object sender, RoutedEventArgs e)
        {
            _autoScroll = true;
            scrollEndBtn.Visibility = Visibility.Collapsed;
            mainScroll.ScrollToEnd();
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            Logger.Info("加载");
            mainScroll.ScrollToEnd();
        }
    }
}
